<template>
  <div class="file-upload-container">
    <h3>文件上传</h3>
    <div class="upload-form">
      <div class="form-group">
        <label for="departmentSelect">选择科室</label>
        <select id="departmentSelect" v-model="selectedDepartment">
          <option value="null">无科室（全局文件）</option>
          <option v-for="dept in departments" :key="dept.id" :value="dept.id">{{ dept.name }}</option>
        </select>
      </div>

      <div class="form-group">
        <label for="fileInput">选择文件</label>
        <input
          type="file"
          id="fileInput"
          @change="handleFileChange"
          accept=".doc,.docx,.pdf"
        >
      </div>
      
      <div class="form-group">
        <label for="folderInput">选择文件夹</label>
        <input
          type="file"
          id="folderInput"
          @change="handleFolderChange"
          webkitdirectory
          directory
        >
        <p v-if="selectedFile" class="file-info">{{ selectedFile.name }} ({{ formatFileSize(selectedFile.size) }})</p>
  <p v-else class="file-info placeholder">未选择文件</p>
  
  <p v-if="selectedFolder" class="file-info">{{ selectedFolder.name }} (包含 {{ folderFiles.length }} 个文件)</p>
  <p v-else-if="folderFiles.length > 0" class="file-info">{{ folderFiles.length }} 个文件夹文件等待上传</p>
  <p v-else class="file-info placeholder">未选择文件夹</p>
      </div>

      <button
        class="upload-btn"
        @click="handleUpload"
        :disabled="!selectedFile && folderFiles.length === 0"
      >
        {{ selectedFile ? '上传文件' : '上传文件夹' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getDepartments } from '@/services/api';
import { useDepartmentsStore } from '@/stores/departments';

// 定义props
const props = defineProps({
  defaultDepartmentId: {
    type: Number,
    default: null
  }
});

// 定义emit
const emit = defineEmits(['upload-success']);

// 响应式数据
const selectedDepartment = ref(null);
const selectedFile = ref(null);
const selectedFolder = ref(null);
const folderFiles = ref([]);
const departments = ref([]);

// 组件挂载时设置默认科室并获取部门数据
onMounted(async () => {
  if (props.defaultDepartmentId !== null) {
    selectedDepartment.value = props.defaultDepartmentId;
  }

  try {
    const response = await getDepartments();
    departments.value = response.data.departments;
  } catch (error) {
    console.error('获取部门数据失败:', error);
    alert('获取部门数据失败，请重试');
  }
});

// 处理文件选择
const handleFileChange = (e) => {
  const file = e.target.files[0];
  console.log('输出选择的文件内容',e.target.files);
  if (file) {
    // 检查文件类型
    console.log('选择的文件:', file.name);
    const fileExtension = file.name.split('.').pop().toLowerCase();
    if (['doc', 'docx', 'pdf'].includes(fileExtension)) {
      selectedFile.value = file;
      selectedFolder.value = null;
      folderFiles.value = [];
      console.log('文件赋值',selectedFile.value);
    } else {
      alert('只能上传Word或PDF文件');
      e.target.value = '';
    }
  }
};

// 处理文件夹选择
const handleFolderChange = (e) => {
  const files = e.target.files;
  if (files.length > 0) {
    // 重置文件选择
    selectedFile.value = null;
    
    // 获取第一个文件的webkitRelativePath来提取文件夹名称
    const firstFilePath = files[0].webkitRelativePath;
    const folderName = firstFilePath.split('/')[0];
    
    selectedFolder.value = { name: folderName };
    folderFiles.value = Array.from(files).filter(file => {
      // 只保留Word和PDF文件
      const fileExtension = file.name.split('.').pop().toLowerCase();
      return ['doc', 'docx', 'pdf'].includes(fileExtension);
    });
    
    console.log('选择的文件夹:', folderName);
    console.log('筛选后的文件夹文件数量:', folderFiles.value.length);
  }
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 上传文件或文件夹
const handleUpload = async () => {
  if (!selectedFile.value && folderFiles.value.length === 0) return;

  try {
    // 获取store
    const store = useDepartmentsStore();

    if (selectedFile.value) {
      // 单个文件上传
      const formData = new FormData();
      formData.append('file', selectedFile.value);
      if (selectedDepartment.value !== null) {
        formData.append('department_id', selectedDepartment.value);
      }
      
      // 调用store方法上传文件
      await store.addFile(formData);

      // 重置表单
      selectedFile.value = null;
      document.getElementById('fileInput').value = '';
      alert('文件上传成功！');
    } else if (folderFiles.value.length > 0) {
      // 文件夹上传
      // 确保folderName始终有值
      const folderName = selectedFolder.value?.name || folderFiles.value[0]?.webkitRelativePath.split('/')[0] || '未命名文件夹';
      let successCount = 0;
      let errorCount = 0;
      
      for (const file of folderFiles.value) {
        try {
          const formData = new FormData();
          formData.append('file', file);
          if (selectedDepartment.value !== null) {
            formData.append('department_id', selectedDepartment.value);
          }
          // 添加文件夹信息
          formData.append('folder_name', folderName);
          
          // 调用store方法上传文件
          await store.addFile(formData);
          successCount++;
        } catch (fileError) {
          console.error(`文件 ${file.name} 上传失败:`, fileError);
          errorCount++;
        }
      }
      
      // 重置表单
      selectedFolder.value = null;
      folderFiles.value = [];
      document.getElementById('folderInput').value = '';
      
      alert(`文件夹上传完成！成功: ${successCount} 个, 失败: ${errorCount} 个`);
    }

    // 触发上传成功事件
    emit('upload-success');
  } catch (error) {
    console.error('上传失败:', error);
    // 显示更详细的错误信息
    alert(`上传失败: ${error.message || '未知错误'}`);
  }
};
</script>

<style scoped>
.file-upload-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h3 {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.upload-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

label {
  font-weight: 500;
  color: #555;
}

select,
input[type="file"] {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.file-info {
  margin: 5px 0 0 0;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 4px;
  font-size: 14px;
}

.placeholder {
  color: #999;
  font-style: italic;
}

.upload-btn {
  padding: 12px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.upload-btn:hover:not(:disabled) {
  background-color: #3aa876;
}

.upload-btn:disabled {
  background-color: #a0a0a0;
  cursor: not-allowed;
}
</style>